local CommonOHOH = _G.CommonOHOH;
local M = CommonOHOH.class.new(script,script.Parent.base,script.Parent.Name);

local Game_Cfg=_G.CommonOHOH.config.Game


function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);

    --监听自动输入按钮
    self.parent.AutoTrainEvent:Connect(function(isAuto)
        if isAuto then
            self:Auto()
        else
            self:CloseAuto()
        end
	end)

     --开启攻击CD检测
    self:OpenAttackCdCheck()

    self.player.BattleSateEvent:Connect(function(isBattle,battle)
        if  isBattle then
            --关闭攻击CD检测
            self:CloseAttackCdCheck()
        else
            --开启攻击CD检测
            self:OpenAttackCdCheck()
        end
    end)
end;

--寻找被激活的训练对象
function M.GetActiveTrianObj(self)

    for k,v in pairs( self.TrianList) do
        if v:IsActive() then
            return v
        end
    end
end

local gAutoTrianCdScale=Game_Cfg.gAutoTrianCdScale

-- 自动输入
function M.Auto(self)
    if  self.autoConnect then
        return 
    end

    local to=self:GetOneOptimalTian()
    local att=to:GetAutoTrinAtt()
    self.parent.character:SetCFrame(att.WorldCFrame)

    self.autoConnect= self:AddStepUpdate(function()

        local trianObj=self:GetActiveTrianObj()
        if  trianObj then
           self.parent.TryAttackEvent:Action(gAutoTrianCdScale)
         end
    end)

end

-- 停止自动输入
function M.CloseAuto(self)
    if self.autoConnect then
        self.autoConnect:Disconnect()
        self.autoConnect=nil
    end
end


function M.dtor(self)
    if self.autoConnect then
        self.autoConnect:Disconnect()
        self.autoConnect=nil
    end
	M.super.dtor(self);
end


--实现这个函数，才能训练自动跳转
function M.isInOneWorld(self,obj)
    local tid=obj:GetTid()
    local index=math.floor((tid-1)/3)+1
   return index==self.parent:GetComponent(_G.CommonOHOH.load.Common_TeleportCtrl()):GetActiveChapId()
end

-- 返回一个训练值最高的对象
function M.GetOneOptimalTian(self)
    local tobj={}
    local maxSort=0
    for _,v in pairs(self.TrianList) do
        if self:isInOneWorld(v) and v:IsUnLock() then
            local sort=v:GetAdd()
            if sort>maxSort then
                maxSort=sort
            end
            if not tobj[sort] then
                tobj[sort]={}
            end
            table.insert(tobj[sort],v)
        end
    end
    local list=tobj[maxSort]
    local index= math.random(1,#list)
	return list[index]
end


return M